<template>
  <view>
    <wd-row class="p-4">
      <view class="scan-card">
        <view class="scan-content">
          <wd-row>
            <wd-col>
              <wd-text text="出库单号：" size="28rpx" class="label-text"></wd-text>
              <wd-text :text="outStockInfo.code" size="28rpx" bold color="#3e7bfa"></wd-text>
            </wd-col>
          </wd-row>
          <wd-row>
            <wd-col>
              <wd-text text="创建时间：" size="28rpx" class="label-text"></wd-text>
              <wd-text :text="outStockInfo.createTime" size="28rpx" bold color="#3e7bfa"></wd-text>
            </wd-col>
          </wd-row>
        </view>
      </view>
    </wd-row>
  </view>

  <wd-tabs v-model="tab" @tap="changeTabs">
    <wd-tab title="出库建议" name="出库建议" v-if="outStockInfo.status != 5">
      <view class="grid">
        <scroll-view scroll-y style="max-height: 650rpx; overflow-y: auto">
          <view v-for="(ele, index) in outStockRecInLocation" :key="index" class="suggest-list">
            <view class="product-header">
              <wd-icon name="bags" color="#3e7bfa"></wd-icon>
              <wd-text :text="ele.productName" size="32rpx" bold color="#3e7bfa"></wd-text>
            </view>

            <view class="location-grid">
              <view
                v-for="(location, locIndex) in ele.locations || []"
                :key="locIndex"
                class="location-item"
              >
                <view class="location-card">
                  <view class="info-row">
                    <view>
                      <wd-icon name="barcode" color="#666"></wd-icon>
                      筐码：
                    </view>
                    <view>
                      <wd-text
                        :text="location.basket || '无筐号'"
                        size="28rpx"
                        color="#333"
                      ></wd-text>
                    </view>
                  </view>
                  <view class="info-row">
                    <view>
                      <wd-icon name="location" color="#666"></wd-icon>
                      储位：
                    </view>
                    <view>
                      <wd-text
                        :text="location.location ? location.location : '无推荐储位'"
                        size="28rpx"
                        color="#333"
                      ></wd-text>
                    </view>
                  </view>
                  <view class="info-row">
                    <view>
                      <wd-icon name="discount" color="#666"></wd-icon>
                      数量：
                    </view>
                    <view>
                      <wd-text
                        :text="location.qty ? location.qty.toFixed(2) + `` : '无'"
                        size="28rpx"
                        color="#333"
                      ></wd-text>
                    </view>
                  </view>
                </view>
              </view>

              <view v-if="!ele.locations?.length" class="empty-location">
                <wd-text text="暂无推荐储位信息" size="28rpx" color="#999"></wd-text>
              </view>
            </view>
          </view>
        </scroll-view>

        <view class="bottom-button">
          <wd-button :round="false" block @tap="handleGenerate()">生成出库建议</wd-button>
        </view>
      </view>
    </wd-tab>
    <wd-tab title="产品信息" name="产品信息" v-if="outStockInfo.status != 5">
      <view class="product-list">
        <view v-for="ele in outStockInfo.stockTranDetailList" :key="ele.id" class="product-item">
          <view class="product-header">
            <wd-icon name="goods" color="#3e7bfa"></wd-icon>
            <wd-text :text="ele.productName" size="32rpx" bold color="#3e7bfa"></wd-text>
          </view>

          <view class="quantity-grid">
            <view class="quantity-item">
              <wd-text text="待出数量" size="28rpx" color="#666"></wd-text>
              <wd-text
                :text="`${ele.qty - ele.locationQty.reduce((total, qty) => total + qty.qty, 0) < 0 ? 0 : (ele.qty - ele.locationQty.reduce((total, qty) => total + qty.qty, 0)).toFixed(2)}${formatUnit(ele.unit)}`"
                size="32rpx"
                bold
                color="#333"
              ></wd-text>
            </view>
            <view class="quantity-item">
              <wd-text text="已出数量" size="28rpx" color="#666"></wd-text>
              <wd-text
                :text="`${ele.locationQty.reduce((total, qty) => total + qty.qty, 0) < 0 ? 0 : ele.locationQty.reduce((total, qty) => total + qty.qty, 0).toFixed(2)}${formatUnit(ele.unit)}`"
                size="32rpx"
                bold
                color="#52c41a"
              ></wd-text>
            </view>
          </view>
        </view>
      </view>
    </wd-tab>
    <wd-tab title="出库明细" name="出库明细">
      <view class="flex flex-col">
        <scroll-view scroll-y style="max-height: 800rpx; overflow-y: auto">
          <view class="stock-list">
            <view v-if="scanDataList.length">
              <wd-swipe-action
                v-for="ele in scanDataList"
                :key="ele.id"
                @tap="handleDelScan($event, ele.id)"
              >
                <view class="detail-card">
                  <view class="card-header">
                    <wd-icon name="barcode" color="#3e7bfa"></wd-icon>
                    <wd-text :text="`筐号：${ele.basket}`" size="34rpx" color="#3e7bfa"></wd-text>
                  </view>

                  <view class="card-body">
                    <view class="info-row">
                      <view class="info-item">
                        <wd-icon name="goods" color="#666"></wd-icon>
                        <wd-text :text="ele.productName" color="#333"></wd-text>
                      </view>
                      <view class="info-item">
                        <wd-icon name="balance" color="#666"></wd-icon>
                        <wd-text :text="`${ele.qty.toFixed(2)}`" color="#333"></wd-text>
                      </view>
                    </view>

                    <view class="info-row">
                      <view class="info-item">
                        <view>
                          <wd-icon name="location" color="#666"></wd-icon>
                          <wd-text text="储位" color="#333"></wd-text>
                        </view>
                      </view>
                      <view class="info-item">
                        <wd-text
                          :text="ele.location ? ele.location : '无储位'"
                          color="#666"
                        ></wd-text>
                      </view>
                    </view>
                  </view>
                </view>

                <template #right v-if="outStockInfo.status !== 5">
                  <view class="delete-btn">
                    <wd-icon name="delete" size="22px" color="#ff4d4f"></wd-icon>
                  </view>
                </template>
              </wd-swipe-action>
            </view>
            <view v-else class="empty">
              <wd-text text="暂无出库记录" size="28rpx" color="#999"></wd-text>
            </view>
          </view>
        </scroll-view>
        <view class="bottom-button">
          <!-- <wd-button @tap="getScanData('w175')">扫码</wd-button> -->
          <wd-button block @tap="handleSubmit" :round="false" v-if="outStockInfo.status !== 5">
            提交
          </wd-button>
        </view>
      </view>
    </wd-tab>
  </wd-tabs>

  <scan-code @scanSuccess="getScanData" />
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import scanCode from '@/components/scanCode/scanCode.vue'
import inOrOutStockApi, {
  TransferOrderItem,
  TransferData,
  InOrOutStockScanData,
  OutStockRecInLocationData,
  BaseResponse,
  OutStockRecInLocationDataV2,
  ScanInStockData,
} from '@/api/inOrOutStock'
import { useMessage, useToast } from 'wot-design-uni'
import ScanCodeApi, { ScanProductList, ScanPatternType, scanProductInfo } from '@/api/scanCode'
import { formatUnit } from '@/utils/unit'
const message = useMessage()
const toast = useToast()
// 出库单信息
const outStockInfo = ref<TransferData>({})

// 根据出库单查询出库单信息
const getTStockTranHead = (outCode: string) => {
  inOrOutStockApi
    .getTStockTranHeadList({
      code: outCode,
      iocode: 'o',
      pageNum: 1,
      pageSize: 1,
    })
    .then((res: any) => {
      outStockInfo.value = res.data.list[0]
      console.log(outStockInfo.value, 'getTStockTranHead')
    })
}
// 出库单号
const outCode = ref('')

const tab = ref('出库明细')

const changeTabs = async (val) => {
  console.log(val.name)

  console.log(outStockInfo.value)
  if (val.name === '出库建议') {
    handleGenerate(outCode.value)
  }
  if (val.name === '产品信息') {
    getTStockTranHead(outCode.value)
  }
  if (val.name === '出库明细') {
    refreshScanList()
  }
}

// 重复扫码校验
const isBasketScanned = (code: string): boolean => {
  if (ScanPatternType.BASKET_CODE_TIMESTAMP.test(code)) {
    const [basket] = code.split(';')

    return scanDataList.value.some((item) => {
      console.log(item, '1222')
      return item.basket === basket
    })
  } else if (ScanPatternType.BASKET_CODE.test(code)) {
    return scanDataList.value.some((item) => {
      console.log(item.basket, code, item.basket === code)

      return item.basket === code
    })
  }
}

// 已扫码数据
const scanDataList = ref<InOrOutStockScanData[]>([])
const getScanData = async (code: string) => {
  try {
    // 筐码
    if (
      !(ScanPatternType.BASKET_CODE.test(code) || ScanPatternType.BASKET_CODE_TIMESTAMP.test(code))
    ) {
      return toast.error('请扫描筐码或标签码')
    }

    console.log(isBasketScanned(code), '122')

    const isScanned = isBasketScanned(code)
    if (isScanned) return toast.error('该条形码已扫描，请勿重复操作')

    const processProduct = async (productInfo: ScanInStockData) => {
      console.log(productInfo, '扫码产品')

      const targetProduct = outStockInfo.value.stockTranDetailList?.find(
        (ele) => ele.productCode === productInfo.productCode,
      )

      if (!targetProduct) {
        return toast.error('出库单不存在该产品')
      }

      await saveBasketDetail(productInfo)
    }

    if (ScanPatternType.BASKET_CODE_TIMESTAMP.test(code)) {
      const [basketCode, productCode, productName, qty] = code.split(';')
      if (qty && productCode && productName && basketCode) {
        await processProduct({
          basket: basketCode,
          productCode,
          productName,
          qty: Number(qty),
          tranCode: outStockInfo.value.code,
        })
      } else {
        return toast.error('无效的筐码格式')
      }
    } else {
      const { data: productInfo } = await ScanCodeApi.getBasketRecordByCode(code)
      if (!productInfo?.productCode) {
        return toast.error('获取产品信息失败')
      }
      console.log(productInfo, '扫码产品信息')

      await processProduct({
        basket: productInfo.parentCode,
        productCode: productInfo.productCode,
        productName: productInfo.productName,
        qty: productInfo.qty,
        tranCode: outStockInfo.value.code,
      })
    }
    await refreshScanList()
  } catch (error) {
    console.error('扫码处理异常:', error)
    // toast.error('扫码处理失败，请重试')
  }
}

// 公共保存方法
const saveBasketDetail = async (productInfo: ScanInStockData) => {
  return inOrOutStockApi.saveOrUpdateTStockTranBasketDetail({
    ...productInfo,
    tranCode: outStockInfo.value.code,
  })
}

// 更新数据列表
const refreshScanList = async () => {
  const res = await inOrOutStockApi.getTStockTranBasketDetailByCode(outCode.value)
  console.log(res, 'res')
  scanDataList.value = [...(res.data as TransferOrderItem[])]
}

const handleDelScan = (event, id) => {
  if (event.value === 'right') {
    // 提示
    message
      .confirm({
        msg: '确定删除吗？',
        title: '警告',
      })
      .then(() => {
        inOrOutStockApi.delTStockTranHead(id).then(() => {
          toast.success('删除成功')
          refreshScanList()
        })
      })
      .catch(() => {
        console.log('点击了取消按钮')
      })
      .finally(() => {})
  }
}

// 解构出库单推荐库位
/**
 * 递归检查响应结构中的错误码
 * @param response 接口响应数据(支持对象/数组嵌套结构)
 */
function checkResponseCode(response: any): void {
  // 处理数组情况
  if (Array.isArray(response)) {
    for (const item of response) {
      checkResponseCode(item)
    }
    return
  }

  // 处理对象情况
  if (response && typeof response === 'object') {
    // 检查当前层级的错误码
    if (response.code === 1) {
      throw new Error(response.msg || '业务异常')
    }

    // 递归检查嵌套数据
    if (response.data) {
      if (Array.isArray(response.data)) {
        checkResponseCode(response.data)
      } else if (typeof response.data === 'object') {
        checkResponseCode(response.data)
      }
    }
  }
}

onLoad(async (option) => {
  outCode.value = option.outCode
  await getTStockTranHead(option.outCode)

  changeTabs({ name: '出库明细' })
})

onShow(() => {})

// 页面隐藏注销事件
onHide(() => {})

const handleSubmit = () => {
  if (scanDataList.value.length === 0) {
    toast.error('请扫码后再提交')
    return
  }
  inOrOutStockApi.submitTStockTranHead(outStockInfo.value.id).then((res) => {
    console.log(res)
    toast.success('提交成功')

    uni.navigateBack()
  })
}
// 出库建议列表
const outStockRecInLocation = ref<OutStockRecInLocationDataV2[]>([])
// 生成出库建议
const handleGenerate = (code: string = outStockInfo.value.code) => {
  // 出库单，产品
  inOrOutStockApi.getOutLocation(code).then((res) => {
    console.log(res)
    outStockRecInLocation.value = handleOutStockResponse(res.data)
  })
}

/**
 * 处理出库建议接口响应
 * @param response 接口响应对象
 * @returns 格式化后的出库建议数据
 */
function handleOutStockResponse(
  response: BaseResponse<OutStockRecInLocationData[]>[],
): OutStockRecInLocationDataV2[] {
  const formattedData: OutStockRecInLocationDataV2[] = []
  response.forEach((item) => {
    console.log(item, 'item')

    const productInfo: OutStockRecInLocationDataV2 = {
      locations: [],
      productCode: '',
      productName: '',
    }
    productInfo.productCode = item.data[0]?.productCode
    productInfo.productName = item.data[0]?.productName

    const { data } = item

    if (data) {
      data.forEach((item) => {
        productInfo.locations.push({
          basket: item.basket,
          location: item.location,
          qty: item.qty,
        })
      })
    }
    formattedData.push(productInfo)
  })
  console.log(formattedData, 'formattedData')

  return formattedData
}
</script>
<style lang="scss" scoped>
.product-card {
  padding: 10px;
}

.bottom-button {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  height: 80rpx;
  padding: 20rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

  :deep(.wd-row) {
    margin: 0 -10rpx;

    .wd-col {
      padding: 0 10rpx;
    }
  }
}
.delete-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  margin: 0 10rpx;
  color: red;
}

.storage-info {
  padding-top: 25rpx;
  .storage-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .storage-cells {
      display: flex;
      justify-content: space-around;

      width: 100%;
      .storage-cell {
        padding: 8rpx 16rpx;
        font-size: 15px;

        color: #2c3e50;

        border-radius: 6rpx;
      }
    }
  }
}
.stock-list {
  padding: 20rpx;

  .detail-card {
    padding: 24rpx;
    margin-bottom: 20rpx;
    background: #fff;
    border: 1rpx solid #eee;
    border-radius: 12rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  }

  .card-header {
    display: flex;
    align-items: center;
    padding-bottom: 20rpx;

    border-bottom: 1rpx solid #eee;
    .wd-icon {
      margin-right: 12rpx;
    }
  }

  .card-body {
    padding-top: 20rpx;
  }

  .info-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20rpx;
  }

  .info-item {
    display: flex;
    align-items: center;

    .wd-icon {
      margin-right: 8rpx;
    }
  }
}
.empty {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  font-size: 14px;
  color: #8492a6;
}

.suggest-list {
  padding: 10rpx;
  margin: 20rpx;
  border: 1rpx solid #eee;
  border-radius: 10rpx;
  box-shadow: 0 0 10rpx 0 rgba(0, 0, 0, 0.1);
  .product-info {
    display: flex;
    justify-content: space-around;
    padding: 10px;
  }
}

.product-header {
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.location-grid {
  display: grid;
  grid-template-columns: repeat(1, 1fr);
  gap: 20rpx;
}

.location-item {
  break-inside: avoid;
}

.location-card {
  padding: 24rpx;

  border-radius: 12rpx;
  box-shadow: 0 0 10rpx 0 rgba(0, 0, 0, 0.1);
  .info-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.empty-location {
  grid-column: 1 / -1;
  padding: 40rpx 0;
  color: #999;
  text-align: center;
}

.product-list {
  padding: 20rpx;

  .product-item {
    padding: 24rpx;
    margin-bottom: 20rpx;
    background: #fff;
    border-radius: 12rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  }

  .quantity-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 30rpx;
    padding: 20rpx;
    margin-top: 20rpx;
    background: #f8f9fa;
    border-radius: 8rpx;
  }

  .quantity-item {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
}
</style>
